package com.risetek.tft.context;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.risetek.tft.entity.TLogs;
import com.risetek.tft.entity.TManager;
import com.risetek.tft.entity.TOperate;
import com.risetek.tft.service.LogsService;
import com.risetek.tft.service.ManagerService;
import com.zlinepay.common.util.AuthCodeUtils;
import com.zlinepay.framework.web.util.RequestUtils;

 

/**
 * 
 * 包括登录信息
 * 
 */
public class AdminContextInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminContextInterceptor.class);

	private void login(HttpServletRequest request, HttpServletResponse response) {
		try {
			String requestType = request.getHeader("X-Requested-With");
			if("XMLHttpRequest".equals(requestType)) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/json");
				response.setDateHeader("Expires", 0);
				response.getWriter().write("{\"sessionTimeout\": true}");
			} else {
				response.sendRedirect(loginUrl);
			}
			request.setAttribute(Constants.MESSAGE, "未登录");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 可以进行编码、安全控制等处理；
		//test();
		String uri = RequestUtils.getURI(request);
		// 登录验证的范围内
		boolean checkLogin = true;		for (String url : excludeUrls) {
			if(uri.matches(url)) {
				checkLogin = false;
				break;
			}
		}
		TManager member = null;
		String seccode = request.getParameter(Constants.AUTHCODE);
		if (StringUtils.isNotEmpty(seccode)) {
			try {
				String[] enccode = AuthCodeUtils.decryptAuthCode(seccode, Constants.AUTHCODE_SEPERATOR);
//				long time = Long.parseLong(enccode[0]);
//				long now = System.currentTimeMillis();
//				int l = (int) (now - time) / 60000;// 分钟
//				if (l < sessionTimeout) {
					Integer userid = Integer.valueOf(enccode[1]);
					member = managerService.findById(userid);
//				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			HttpSession session = request.getSession();
			Integer userid = (Integer) session.getAttribute(Constants.USERID_IN_SESSION);
			if (userid != null) {
				member = managerService.findById(userid);
			}
		}
		// 判断登录是否有效
		if(checkLogin) {
			if (member == null || !member.getState()) {
				login(request, response);
				return false;
			}
//			member = managerService.get(1);
		}
		if(member != null) {
			request.setAttribute(Constants.USER_IN_REQUEST, member);
			String enccode = AuthCodeUtils.encryptAuthCode(Constants.AUTHCODE_SEPERATOR, System.currentTimeMillis(), member.getManagerid());
			request.setAttribute(Constants.AUTHCODE, enccode);
		}
	
		request.setAttribute(Constants.SYS_CONFIG_KEY, Sysconfig.getAll());
		request.setAttribute("ctx", request.getContextPath());
		return true;
	}
	
	
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		// 有机会修改ModelAndView；		// 操作成功，重新跳转	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String uri = RequestUtils.getURI(request);
		if("1".equals(Sysconfig.get(Constants.OPENSYSLOG)) && !uri.startsWith("/op_") && Constants.POST.equals(request.getMethod())) {
			TOperate operate = (TOperate) request.getAttribute(Constants.OP_IN_REQUEST);
			TLogs logs = new TLogs();
			String message = null;
			if (ex != null) {
				message = ex.getMessage();
			} else {
				message = (String) request.getAttribute(Constants.MESSAGE);
			}
			TManager account = (TManager) request.getAttribute(Constants.USER_IN_REQUEST);
			if (account != null) {
				logs.setAccount(account.getAccount());
			}
			String param = RequestUtils.getQueryString(request);
			if (operate != null) {
				logs.setTitle(operate.getTMenu().getName() + "-"
						+ operate.getName());
			} else {
				logs.setTitle((String) request.getAttribute(Constants.TITLE));
			}
			logs.setParams(param);
			logs.setUrl(request.getRequestURL().toString());
			logs.setMessage(message);
			logs.setIp(RequestUtils.getIpAddr(request));
			logs.setOptime(new Timestamp(System.currentTimeMillis()));
			logs.setId(333344); 
			logsService.save(logs);
		}

		if (ex != null) {
			logger.error("", ex);
			try {
				String requestType = request.getHeader("X-Requested-With");
				if("XMLHttpRequest".equals(requestType)) {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("text/json");
					response.setDateHeader("Expires", 0);
					//response.getWriter().write("{\"error\": \"对不起，服务器异常，请稍后再试。\"}");
					response.getWriter().write("{\"error\": \""+ex.getMessage()+"\"}");
				} else {
					//response.sendRedirect("");
					response.getWriter().write(ex.getMessage());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Autowired
	private ManagerService managerService;
	@Autowired
	private LogsService logsService;
	private List<String> excludeUrls = new ArrayList<String>();
	private String loginUrl;
	private int sessionTimeout = 10;

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public void setSessionTimeout(int sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}
	private void test(){
		System.out.println(""
			    
 +"                  _ooOoo_\r\n"
 +"                 o8888888o\r\n"
 +"                 88\" . \"88\r\n"
 +"                 (| -_- |)\r\n"
 +"                 O\\  =  /O\r\n"
 +"              ____/`---'\"____\r\n"
 +"            .'  \\|     |//  `.\r\n"
 +"           /  \\|||  :  |||//  \\\r\n"
 +"          /  _||||| -:- |||||-  \\\r\n"
 +"          |   | \\\\  -  /// |   |\r\n"
 +"          | \\_|  ''\\---/''  |   |\r\n"
 +"          \\  .-\\__  `-`  ___/-. /\r\n"
 +"        ___`. .'  /--.--\\  `. .\" __\r\n"
 +"     .\"\" '<  `.___\\_<|>_/___.'  >'\"\".\r\n"
 +"    | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |\r\n"
 +"    \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /\r\n"
 +"======`-.____`-.___\\_____/___.-`____.-'======\r\n"
 +"                 `=---='\r\n"
+"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n"
+" 佛祖保佑       永无BUG\r\n"
+"\r\n"
+"        佛曰:\r\n"    
+"                  写字楼里写字间，写字间里程序员；\r\n "   
+"                  程序人员写程序，又拿程序换酒钱。\r\n"    
+"                  酒醒只在网上坐，酒醉还来网下眠；\r\n "   
+"                  酒醉酒醒日复日，网上网下年复年。\r\n"    
+"                  但愿老死电脑间，不愿鞠躬老板前； \r\n"   
+"                  奔驰宝马贵者趣，公交自行程序员。  \r\n " 
+"                  别人笑我忒疯癫，我笑自己命太贱；  \r\n"  
+"                  不见满街漂亮妹，哪个归得程序员？");
	}
}